package com.csx.governance.traffic.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.lang.NonNullApi;

import java.util.List;

/**
 * 负责在启动时 或者 配置变更时刷新 流量治理配置
 * @author cuisongxu
 * @date 2023/2/23 17:31
 */
public class TrafficGovernanceRuleRefreshListener implements SmartApplicationListener {

    private static final Logger logger = LoggerFactory.getLogger(TrafficGovernanceRuleRefreshListener.class);

    private final List<TrafficGovernanceRuleLocator<?>> trafficGovernanceRuleLocators;

    public TrafficGovernanceRuleRefreshListener(List<TrafficGovernanceRuleLocator<?>> trafficGovernanceRuleLocators) {
        this.trafficGovernanceRuleLocators = trafficGovernanceRuleLocators;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType.equals(ContextRefreshedEvent.class) || eventType.equals(RefreshScopeRefreshedEvent.class);
    }

    @Override
    public void onApplicationEvent(@NonNull ApplicationEvent event) {
        trafficGovernanceRuleLocators.forEach(TrafficGovernanceRuleLocator::refresh);
        logger.info("All Traffic Governance Rule finish refresh");
    }
}
